package com.baize.markwondemo.spans;

import android.util.Log;
import android.util.LruCache;

/**
 * 防剧透Span的状态管理，防止TextView更新后防剧透被重置
 */
public class MaskTextSpanStateManager {

  private static volatile MaskTextSpanStateManager mInstance;

  private MaskTextSpanStateManager() {
  }

  public static MaskTextSpanStateManager getInstance() {
    if (mInstance == null) {
      synchronized (MaskTextSpanStateManager.class) {
        if (mInstance == null) {
          mInstance = new MaskTextSpanStateManager();
        }
      }
    }
    return mInstance;
  }

  private LruCache<Integer, Boolean> lruCache;

  public void cache(int key, boolean value) {
    if (lruCache == null) {
      lruCache = new LruCache<Integer, Boolean>(100);
    }
    lruCache.put(key, value);
    Log.i("baize_", "cache: " + key + " " + value);
  }

  public boolean get(int key) {
    if (key == -1) return true;
    if (lruCache == null) return true;
    Boolean state = lruCache.get(key);
    Log.i("baize_", "get: " + key + " " + state);
    return state == null || state;
  }

  /**
   * 拿到缓存值后将结果反转
   */
  public boolean getAndRevert(int key) {
    boolean state = get(key);
    cache(key, !state);
    return state;
  }

  public void clear() {
    lruCache.evictAll();
    lruCache = null;
    mInstance = null;
  }

}
